//
//  XKLoginView.m
//  xk100
//
//  Created by xiaokang on 2017/6/6.
//  Copyright © 2017年 xiaokang. All rights reserved.
//

#import "XKLoginView.h"

@interface XKLoginView () <UITextFieldDelegate>

@property (nonatomic, strong) UIImageView *backgroundImageView; // 背景图片
@property (nonatomic, strong) UIImageView *logoImageView;       // 公司Logo

@property (nonatomic, strong) UITextField *phoneTextField;      // 手机号
@property (nonatomic, strong) UITextField *passwordTextField;   // 登录密码
@property (nonatomic, strong) UIView      *phoneLineView;       // 白线(手机下)
@property (nonatomic, strong) UIView      *passwordLineView;    // 白线(密码下)
@property (nonatomic, strong) UIButton *rememberPasswordButton; // 记住密码
@property (nonatomic, strong) UIButton *forgetPasswordButton;   // 忘记密码
@property (nonatomic, strong) UIButton *loginButton;            // 登录
@property (nonatomic, strong) UIButton *fastRegisterButton;     // 快速注册

@end
@implementation XKLoginView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initSubviews];
    }
    return self;
}

#pragma mark - 初始化控件
- (void)initSubviews {
    /*****************************************************************************/
    _backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_bg"]];
    [self addSubview:_backgroundImageView];
    [_backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    /*****************************************************************************/
    _logoImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_logo"]];
    [self addSubview:_logoImageView];
    [_logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self);
        make.top.mas_equalTo(self).offset(100*Scale_H);
        make.size.mas_equalTo(CGSizeMake(70*Scale_W, 86*Scale_W));
    }];
    
    /*****************************************************************************/
    _phoneTextField = [UITextField new];
    _phoneTextField.delegate = self;
    _phoneTextField.font = Font(18);
    _phoneTextField.textColor = WhiteColor;
    _phoneTextField.borderStyle = UITextBorderStyleNone;
    _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    _phoneTextField.placeholder = @"请输入手机号";
    [_phoneTextField setValue:UIColorFromRGB(0xA1A1A1) forKeyPath:@"_placeholderLabel.textColor"];
    [_phoneTextField setValue:[UIFont systemFontOfSize:18*Scale_W] forKeyPath:@"_placeholderLabel.font"];
    [_phoneTextField addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
    [self addSubview:_phoneTextField];
    [_phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(60*Scale_W);
        make.right.mas_equalTo(self).offset(-60*Scale_W);
        make.top.mas_equalTo(_logoImageView.mas_bottom).offset(30*Scale_W);
        make.height.mas_equalTo(40*Scale_W);
    }];
    
    /*****************************************************************************/
    _phoneLineView = [UIView new];
    _phoneLineView.backgroundColor = kBaseGrayColor;
    [self addSubview:_phoneLineView];
    [_phoneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(50*Scale_W);
        make.right.mas_equalTo(self).offset(-50*Scale_W);
        make.top.mas_equalTo(_phoneTextField.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    
    /*****************************************************************************/
    _passwordTextField = [UITextField new];
    _passwordTextField.delegate = self;
    _passwordTextField.font = Font(18);
    _passwordTextField.textColor = WhiteColor;
    _passwordTextField.borderStyle = UITextBorderStyleNone;
    _passwordTextField.secureTextEntry = YES;
    _passwordTextField.placeholder = @"请输入登录密码";
    [_passwordTextField setValue:UIColorFromRGB(0xA1A1A1) forKeyPath:@"_placeholderLabel.textColor"];
    [_passwordTextField setValue:[UIFont systemFontOfSize:18*Scale_W] forKeyPath:@"_placeholderLabel.font"];
    [_passwordTextField addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
    [self addSubview:_passwordTextField];
    [_passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(_phoneTextField);
        make.top.mas_equalTo(_phoneLineView.mas_bottom).offset(14*Scale_W);
    }];
    
    /*****************************************************************************/
    _passwordLineView = [UIView new];
    _passwordLineView.backgroundColor = kBaseGrayColor;
    [self addSubview:_passwordLineView];
    [_passwordLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(_phoneLineView);
        make.top.mas_equalTo(_passwordTextField.mas_bottom);
    }];
    
    /*****************************************************************************/
    _rememberPasswordButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _rememberPasswordButton.titleLabel.font = Font(15);
    _rememberPasswordButton.isIgnore = YES;
    [_rememberPasswordButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [_rememberPasswordButton setTitle:@"记住密码" forState:UIControlStateNormal];
    [_rememberPasswordButton setImage:[UIImage imageNamed:@"check_box_nor"] forState:UIControlStateNormal];
    [_rememberPasswordButton setImage:[UIImage imageNamed:@"check_box_sel"] forState:UIControlStateSelected];
    [_rememberPasswordButton setImage:[UIImage imageNamed:@"check_box_sel"] forState:UIControlStateHighlighted];
    [_rememberPasswordButton addTarget:self action:@selector(rememberPasswordButtonTouchEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_rememberPasswordButton];
    [_rememberPasswordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_passwordLineView);
        make.top.mas_equalTo(_passwordLineView.mas_bottom).offset(8*Scale_W);
    }];
    
    /*****************************************************************************/
    _forgetPasswordButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _forgetPasswordButton.titleLabel.font = Font(15);
    _forgetPasswordButton.titleLabel.textColor = WhiteColor;
    NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle),
                                 NSForegroundColorAttributeName: [UIColor whiteColor]};
    NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc] initWithString:@"忘记密码?" attributes:attribtDic];
    [_forgetPasswordButton setAttributedTitle:attribtStr forState:UIControlStateNormal];
    [_forgetPasswordButton addTarget:self action:@selector(forgetPasswordButtonTouchEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_forgetPasswordButton];
    [_forgetPasswordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(_passwordLineView);
        make.centerY.mas_equalTo(_rememberPasswordButton);
    }];
    
    /*****************************************************************************/
    _loginButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _loginButton.layer.cornerRadius = 22*Scale_W;
    _loginButton.layer.masksToBounds = YES;
    _loginButton.titleLabel.font = Font(15);
    _loginButton.enabled = NO;
    [_loginButton setTitle:@"登      录" forState:UIControlStateNormal];
    [_loginButton setBackgroundImage:[UIImage imageWithColor:LightGrayColor] forState:UIControlStateDisabled];
    [_loginButton setBackgroundImage:[UIImage imageWithColor:LightGrayColor] forState:UIControlStateSelected];
    [_loginButton setBackgroundImage:[UIImage imageWithColor:kBaseRedColor] forState:UIControlStateNormal];
    [_loginButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [_loginButton setTitleColor:GrayColor forState:UIControlStateDisabled];
    [_loginButton setTitleColor:GrayColor forState:UIControlStateSelected];
    [_loginButton addTarget:self action:@selector(loginButtonTouchEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_loginButton];
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(_passwordLineView);
        make.top.mas_equalTo(_rememberPasswordButton.mas_bottom).offset(20*Scale_W);
        make.height.mas_equalTo(44*Scale_W);
    }];
    
    /*****************************************************************************/
    _fastRegisterButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _fastRegisterButton.layer.cornerRadius = 22*Scale_W;
    _fastRegisterButton.layer.masksToBounds = YES;
    _fastRegisterButton.titleLabel.font = Font(15);
    [_fastRegisterButton setTitle:@"快速注册" forState:UIControlStateNormal];
    [_fastRegisterButton setBackgroundImage:[UIImage imageWithColor:LightGrayColor] forState:UIControlStateDisabled];
    [_fastRegisterButton setBackgroundImage:[UIImage imageWithColor:LightGrayColor] forState:UIControlStateSelected];
    [_fastRegisterButton setBackgroundImage:[UIImage imageWithColor:kBaseRedColor] forState:UIControlStateNormal];
    [_fastRegisterButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [_fastRegisterButton setTitleColor:GrayColor forState:UIControlStateDisabled];
    [_fastRegisterButton setTitleColor:GrayColor forState:UIControlStateSelected];
    [_fastRegisterButton addTarget:self action:@selector(fastRegisterButtonTouchEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_fastRegisterButton];
    [_fastRegisterButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(_loginButton);
        make.top.mas_equalTo(_loginButton.mas_bottom).offset(16*Scale_W);
    }];
    
    
    /*****************************************************************************/
    // 读取账号
    [self readAccountAndPassword];
}

#pragma mark - 读取账号密码
- (void)readAccountAndPassword {
    // 读取账号
    NSString *account = [UserDefaults objectWithKey:@"USER_ACCOUNT"];
    self.phoneTextField.text = [account isMobileNumber]? account :@"";
    
    BOOL isRembered = [[NSUserDefaults standardUserDefaults] boolForKey:@"isRemberPassword"];
    _rememberPasswordButton.selected = isRembered;
    if (isRembered) {
        // 根据账号和唯一标识读取密码
        NSString *password = [SAMKeychain passwordForService:[[NSBundle mainBundle] bundleIdentifier] account:account];
        _passwordTextField.text = password;
        _loginButton.enabled = password.length>5 ? YES : NO;
    }
}

#pragma mark - UITextFieldDelegate代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSMutableString *text = [NSMutableString stringWithString:textField.text];
    [text replaceCharactersInRange:range withString:string];
    if (textField == self.phoneTextField) {
        return (text.length > 11 || ![string isOnlyNumber]) ? NO : YES;
    } else if (textField == _passwordTextField) {
        return text.length > 16 ? NO : YES;
    }
    return YES;
}

#pragma mark - 编辑改变
- (void)textFieldDidChanged:(UITextField *)sender {
    if (_passwordTextField.text.length >= 6 && _phoneTextField.text.length == 11) {
        _loginButton.enabled = YES;
    } else {
        _loginButton.enabled = NO;
    }
}

#pragma mark - 记住密码
- (void)rememberPasswordButtonTouchEvent:(UIButton *)sender {
    sender.selected = !sender.selected;
    [[NSUserDefaults standardUserDefaults] setBool:sender.selected forKey:@"isRemberPassword"];
}

#pragma mark - 忘记密码
- (void)forgetPasswordButtonTouchEvent:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(forgetPasswordWithPhone:)]) {
        [self.delegate forgetPasswordWithPhone:_phoneTextField.text];
    }
}

#pragma mark - 登录
- (void)loginButtonTouchEvent:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(loginWithPhone:password:)]) {
        [self.delegate loginWithPhone:_phoneTextField.text password:_passwordTextField.text];
    }
}

#pragma mark - 快速注册
- (void)fastRegisterButtonTouchEvent:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(fastRegisterWithPhone:)]) {
        [self.delegate fastRegisterWithPhone:_phoneTextField.text];
    }
}



@end
